package com.mySampleApplication.server;


import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.mySampleApplication.client.MySampleApplicationService;
import com.mySampleApplication.client.User;
import com.mySampleApplication.server.database.DatabaseManager;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class MySampleApplicationServiceImpl extends RemoteServiceServlet implements MySampleApplicationService {

    public User addUser(String name, String lastname, String login, String password) {
        String selectTableSQL = "SELECT * from USERS";
        Connection connection = null;
        Statement statement = null;
        boolean flag = true;
        try {
            connection = DatabaseManager.getInstance().createConnection();
            statement = connection.createStatement();
            ResultSet rs = statement.executeQuery(selectTableSQL);

            while (rs.next()) {
                if (name.equals(rs.getString("NAME")) && lastname.equals(rs.getString("LAST_NAME")) && login.equals(rs.getString("LOGIN")) && password.equals(rs.getString("PASSWORD"))){
                    flag = false;
                }
            }
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
        if (flag){
            boolean res = (DatabaseManager.getInstance().add(name, lastname, login, password));
            if (res){
                System.out.println("User has been created");
                return new User(name, lastname, login, password);
            } else {
                System.out.println("Something happened");
                return new User(false);
            }
        } else {
            System.out.println("User exists");
            return new User(true);
        }

    }


}